package com.helsinki.security;

import com.helsinki.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class CustomerAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    // request.getParameter -> application/x-www-form-urlencoded
    // application/json
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 1.获得用户输入的账号密码
        String username = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();
        // 2.调用service,根据账号获得 UserDetails对象 (可能抛出异常)
        UserDetails userDetails = userInfoService.loadUserByUsername(username);

        // 3.对比密码, 第一个是明文密码, 第二个是数据库密码(加密过得)
        if (!passwordEncoder.matches(password, userDetails.getPassword())){
            throw new AuthenticationException("密码错误") {};
        }
        // 4.返回一个身份对象
        return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}